import { ref, computed, onMounted } from 'vue'
import { authService } from '../services'
import { useUserStore } from '../../auth/stores/user'
import { useAuthManager } from '../../auth/composables/useAuthManager'
import type { UserInfo } from '../../../types/api'

/**
 * 认证相关的组合式函数
 */
export function useAuth() {
  const userStore = useUserStore()
  const loading = ref(false)
  const { isAuthenticated, initializeAuth } = useAuthManager()

  // 计算属性 - 使用Pinia状态
  const userInfo = computed(() => userStore.userInfo)
  const isLoggedIn = computed(() => isAuthenticated.value && userInfo.value !== null)
  const userRole = computed(() => userInfo.value?.role || '')
  const username = computed(() => userInfo.value?.nickname || userInfo.value?.username || '')

  /**
   * 初始化认证状态
   */
  const initAuth = async () => {
    loading.value = true
    try {
      // 使用useAuthManager的初始化方法
      await initializeAuth()
    } finally {
      loading.value = false
    }
  }

  /**
   * 登录
   */
  const login = async (username: string, password: string) => {
    loading.value = true
    try {
      await authService.login({
        username: username,
        password: password
      })
      // 用户信息已通过认证服务保存到Pinia
      return true
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  /**
   * 注册
   */
  const register = async (userData: any) => {
    loading.value = true
    try {
      await authService.register(userData)
      return true
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  /**
   * 登出
   */
  const logout = async () => {
    loading.value = true
    try {
      await authService.logout()
      // 认证服务已清除Pinia状态
    } finally {
      loading.value = false
    }
  }

  /**
   * 更新用户信息
   */
  const updateUserInfo = (newUserInfo: Partial<UserInfo>) => {
    userStore.updateUserInfo(newUserInfo)
  }

  // 生命周期
  onMounted(() => {
    initAuth()
  })

  return {
    // 状态
    loading,
    
    // 计算属性 - 使用Pinia状态
    isAuthenticated,
    userInfo,
    isLoggedIn,
    userRole,
    username,
    
    // 方法
    login,
    register,
    logout,
    updateUserInfo,
    initAuth
  }
}

/**
 * 页面加载状态管理
 */
export function useLoading() {
  const loading = ref(false)
  const error = ref<string | null>(null)

  const withLoading = async <T>(operation: () => Promise<T>): Promise<T | null> => {
    loading.value = true
    error.value = null
    try {
      const result = await operation()
      return result
    } catch (err: any) {
      error.value = err.message || '操作失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  return {
    loading,
    error,
    withLoading
  }
}

/**
 * 分页管理
 */
export function usePagination<T>() {
  const list = ref<T[]>([])
  const loading = ref(false)
  const total = ref(0)
  const page = ref(1)
  const size = ref(10)
  const error = ref<string | null>(null)

  const hasMore = computed(() => list.value.length < total.value)

  const reset = () => {
    list.value = []
    total.value = 0
    page.value = 1
    error.value = null
  }

  const loadMore = async (fetchFunction: (page: number, size: number) => Promise<any>) => {
    if (loading.value || !hasMore.value) return

    loading.value = true
    error.value = null
    
    try {
      const response = await fetchFunction(page.value, size.value)
      
      if (page.value === 1) {
        list.value = response.list || []
      } else {
        list.value.push(...(response.list || []))
      }
      
      total.value = response.total || 0
      page.value++
      
      return response
    } catch (err: any) {
      error.value = err.message || '加载失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  return {
    list,
    loading,
    total,
    page,
    size,
    error,
    hasMore,
    reset,
    loadMore
  }
}